from datetime import datetime
from fastapi import APIRouter, Depends, Form, Request
from pydantic_validation_decorator import ValidateFields
from sqlalchemy.ext.asyncio import AsyncSession
from config.enums import BusinessType
from config.get_db import get_db
from module_admin.annotation.log_annotation import Log
from module_admin.aspect.interface_auth import CheckUserInterfaceAuth
from module_admin.entity.vo.user_vo import CurrentUserModel
from module_admin.service.login_service import LoginService
from module_monitor.service.monitor_service import MonitorService
from module_monitor.entity.vo.monitor_vo import DeleteMonitorModel, MonitorModel, MonitorPageQueryModel
from utils.common_util import bytes2file_response
from utils.log_util import logger
from utils.page_util import PageResponseModel
from utils.response_util import ResponseUtil
from utils.model_util import get_video_description, get_img_description


monitorController = APIRouter(prefix='/manage/monitor', dependencies=[Depends(LoginService.get_current_user)])


@monitorController.get(
    '/list', response_model=PageResponseModel, dependencies=[Depends(CheckUserInterfaceAuth('manage:monitor:list'))]
)
async def get_manage_monitor_list(
    request: Request,
monitor_page_query: MonitorPageQueryModel = Depends(MonitorPageQueryModel.as_query),
    query_db: AsyncSession = Depends(get_db),
):
    # 获取分页数据
    monitor_page_query_result = await MonitorService.get_monitor_list_services(query_db, monitor_page_query, is_page=True)
    logger.info('获取成功')

    return ResponseUtil.success(model_content=monitor_page_query_result)


@monitorController.post('', dependencies=[Depends(CheckUserInterfaceAuth('manage:monitor:add'))])
@ValidateFields(validate_model='add_monitor')
@Log(title='监控管理', business_type=BusinessType.INSERT)
async def add_manage_monitor(
    request: Request,
    add_monitor: MonitorModel,
    query_db: AsyncSession = Depends(get_db),
    current_user: CurrentUserModel = Depends(LoginService.get_current_user),
):
    add_monitor.create_by = current_user.user.user_name
    add_monitor.create_time = datetime.now()
    add_monitor.update_by = current_user.user.user_name
    add_monitor.update_time = datetime.now()
    add_monitor_result = await MonitorService.add_monitor_services(query_db, add_monitor)
    logger.info(add_monitor_result.message)

    return ResponseUtil.success(msg=add_monitor_result.message)


@monitorController.put('', dependencies=[Depends(CheckUserInterfaceAuth('manage:monitor:edit'))])
@ValidateFields(validate_model='edit_monitor')
@Log(title='监控管理', business_type=BusinessType.UPDATE)
async def edit_manage_monitor(
    request: Request,
    edit_monitor: MonitorModel,
    query_db: AsyncSession = Depends(get_db),
    current_user: CurrentUserModel = Depends(LoginService.get_current_user),
):
    edit_monitor.update_by = current_user.user.user_name
    edit_monitor.update_time = datetime.now()
    edit_monitor_result = await MonitorService.edit_monitor_services(query_db, edit_monitor)
    logger.info(edit_monitor_result.message)

    return ResponseUtil.success(msg=edit_monitor_result.message)


@monitorController.delete('/{monitor_ids}', dependencies=[Depends(CheckUserInterfaceAuth('manage:monitor:remove'))])
@Log(title='监控管理', business_type=BusinessType.DELETE)
async def delete_manage_monitor(request: Request, monitor_ids: str, query_db: AsyncSession = Depends(get_db)):
    delete_monitor = DeleteMonitorModel(monitorIds=monitor_ids)
    delete_monitor_result = await MonitorService.delete_monitor_services(query_db, delete_monitor)
    logger.info(delete_monitor_result.message)

    return ResponseUtil.success(msg=delete_monitor_result.message)


@monitorController.get(
    '/{monitor_id}', response_model=MonitorModel, dependencies=[Depends(CheckUserInterfaceAuth('manage:monitor:query'))]
)
async def query_detail_manage_monitor(request: Request, monitor_id: int, query_db: AsyncSession = Depends(get_db)):
    monitor_detail_result = await MonitorService.monitor_detail_services(query_db, monitor_id)
    logger.info(f'获取monitor_id为{monitor_id}的信息成功')

    return ResponseUtil.success(data=monitor_detail_result)


@monitorController.post('/export', dependencies=[Depends(CheckUserInterfaceAuth('manage:monitor:export'))])
@Log(title='监控管理', business_type=BusinessType.EXPORT)
async def export_manage_monitor_list(
    request: Request,
    monitor_page_query: MonitorPageQueryModel = Form(),
    query_db: AsyncSession = Depends(get_db),
):
    # 获取全量数据
    monitor_query_result = await MonitorService.get_monitor_list_services(query_db, monitor_page_query, is_page=False)
    monitor_export_result = await MonitorService.export_monitor_list_services(monitor_query_result)
    logger.info('导出成功')

    return ResponseUtil.streaming(data=bytes2file_response(monitor_export_result))

@monitorController.get(
    '/solve/{monitor_id}', response_model=MonitorModel, dependencies=[Depends(CheckUserInterfaceAuth('manage:monitor:query'))]
)
async def solve(request: Request, monitor_id: int, query_db: AsyncSession = Depends(get_db)):
    monitor_detail_result = await MonitorService.monitor_detail_services(query_db, monitor_id)
    file_type = monitor_detail_result.file_type
    if file_type == 'video':
        content = get_video_description(monitor_detail_result.file_url)['现场描述']
    elif file_type == 'image':
        content = get_img_description(monitor_detail_result.file_url)['现场描述']
    else:
        return ResponseUtil.error('文件内容无法解析')
    monitor_detail_result.status = '1'
    monitor_detail_result.content = content
    await MonitorService.edit_monitor_services(query_db, monitor_detail_result)
    logger.info(f'解析monitor_id为{monitor_id}的信息成功')
    return ResponseUtil.success('文件内容解析成功')